from views import *
    
def comprar(request, cope_id):
    """Compra setmanal"""
    user = users.GetCurrentUser()
    if user is None:
      return http.HttpResponseForbidden('You must be signed in to add or edit a ')
    
    # Comprovar si tens compra a mitjes
    
    
    # Carregar productes actius de la teva coperativa
    # 
    cope = Coperativa.get_by_id(int(cope_id))
    
    productes = db.GqlQuery('SELECT * FROM Product WHERE coperativa=:1 and actiu=True', cope)
        
    llistat=[]
    
    for producte in productes:
        compra = db.GqlQuery('SELECT * FROM Compra WHERE usuari=:1 and coperativa=:2 and historica=False and product=:3 ', user, cope, producte)
        if compra.count()>0:
            llistat.append({'obj':producte, 'quantitat':compra[0].quantitat})
        else:
            llistat.append({'obj':producte, 'quantitat':0})

            
    if not request.POST:
      return respond(request, user, 'compra', {'compra': compra,  'cope':cope, 'llistat':llistat})
    
    
    for post in request.POST.keys():
        if post!= 'submit':
            prod = Product.get_by_id(int(post))
            compra = db.GqlQuery('SELECT * FROM Compra WHERE usuari=:1 and coperativa=:2 and historica=False and product=:3 ', user, cope, prod)
            if compra.count()>0:
                compra_final = compra[0]
            else:
                compra_final = Compra()
                compra_final.coperativa = cope
                compra_final.usuari = user
                compra_final.historica = False
                compra_final.product = prod
                compra_final.put()                
            compra_final.quantitat = float(request.POST[post])
            compra_final.save()      
            
    return http.HttpResponseRedirect('/%s/comprar' % cope_id)  
